package com.nbsaas.boot.app.ext.helper;

import com.nbsaas.boot.app.api.domain.simple.AppMenuSimple;
import com.nbsaas.boot.app.ext.domain.simple.AppMenuExtSimple;
import org.springframework.beans.BeanUtils;

import java.util.*;
import java.util.stream.Collectors;

public class TreeHelper {

    public static List<AppMenuExtSimple> makeTree(List<AppMenuSimple> menuList) {
        return makeTree(menuList, false);
    }


    public static List<AppMenuExtSimple> makeTree(List<AppMenuSimple> menuList, Boolean handleDisabled) {
        List<AppMenuExtSimple> tree = new ArrayList<>();
        if (menuList != null && !menuList.isEmpty()) {
            List<AppMenuExtSimple> ls = menuList.stream().map(item -> {
                AppMenuExtSimple simple = new AppMenuExtSimple();
                BeanUtils.copyProperties(item, simple);
                if (simple.getSortNum() == null) {
                    simple.setSortNum(0);
                }
                if (simple.getMenuType() != null && simple.getMenuType() == 1) {
                    //如果是系统菜单  租户管理菜单的时候不能删除已经做任何其他处理
                    simple.setDisabled(handleDisabled);
                }
                return simple;
            }).collect(Collectors.toList());
            Map<Long, AppMenuExtSimple> map = new HashMap<>();
            for (AppMenuExtSimple item : ls) {
                map.put(item.getId(), item);
            }
            for (AppMenuExtSimple item : ls) {
                if (item.getParent() == null) {
                    tree.add(item);
                } else {
                    AppMenuExtSimple parent = map.get(item.getParent());
                    if (parent != null) {
                        if (parent.getChildren() == null) {
                            parent.setChildren(new ArrayList<>());
                        }
                        parent.getChildren().add(item);
                    }
                }
            }

        }
        tree.sort(Comparator.comparingLong(AppMenuExtSimple::getSortNum));

        for (AppMenuExtSimple menuExtSimple : tree) {
            if (menuExtSimple.getChildren() != null) {
                menuExtSimple.getChildren().sort(Comparator.comparingLong(AppMenuSimple::getSortNum));
            }
        }

        return tree;
    }

}
